package cn.sc.summer.job.config;

import cn.sc.summer.constant.util.port.ServerPortUtil;
import cn.sc.summer.exception.util.ip.IPUtil;
import cn.sc.summer.job.property.XXLProperties;
import cn.sc.summer.job.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * xxl-job config
 *
 * @author a-xin 2017-04-28
 */
@Slf4j
@Configuration
public class XxlJobConfig {

    @Resource
    private XXLProperties xxlProperties;

    @Bean
    @ConditionalOnBean(JobService.class)
    @ConditionalOnProperty(prefix = "xxljob", name = "enabled", havingValue = "true")
    public XxlJobExecutorX xxlJobExecutor(JobService jobService) {
        log.info("==> Start initialize the XXLJob distributed timer!");
        XxlJobExecutorX xxlJobExecutorX = new XxlJobExecutorX();
        int addrPort = Integer.parseInt(ServerPortUtil.getAvailablePort());
        xxlJobExecutorX.setJobService(jobService);
        xxlJobExecutorX.setAdminAddresses(xxlProperties.getClientAddress());
        xxlJobExecutorX.setAppname(xxlProperties.getAppName());
        xxlJobExecutorX.setIp(IPUtil.getNacosInstanceIp());
        xxlJobExecutorX.setPort(addrPort);
        xxlJobExecutorX.setAccessToken(xxlProperties.getAccessToken());
        xxlJobExecutorX.setLogPath(xxlProperties.getLogPath());
        xxlJobExecutorX.setLogRetentionDays(xxlProperties.getLogRetentionDays());
        log.info("==> End initialize the XXLJob distributed timer!");
        log.info("==> The " + xxlProperties.getAppName() + " XXLJob initialization: IP : " + IPUtil.getNacosInstanceIp() + ", Port : " + addrPort);
        return xxlJobExecutorX;
    }

}
